import requests
import pymysql
import json
import hashlib
import datetime
import time
from redis import Redis
from utils.environments_json import json_data, urlHead
from utils.autoTestLog import logger
from setupDemo.common_setup import find_user_id_mid

# 数据库连接
mysql_json = json_data.get("mysql")
server = mysql_json.get("server")
port = mysql_json.get("port")
user = mysql_json.get("username")
passwd = mysql_json.get("password")
database = json_data.get(json_data.get("current_env")+"_"+"mysql").get(json_data.get("default_project"))
db1 = pymysql.connect(host=server, port=port, user=user, password=passwd, db=database, charset='utf8',
                      autocommit=True)
cursor = db1.cursor()

# redis连接
redis_json = json_data.get("redis")
server = redis_json.get("server")
port = int(redis_json.get("port"))
passwd = redis_json.get("passwd")
db = json_data.get(json_data.get("current_env")+"_"+"redis").get(json_data.get("default_project"))
redis = Redis(host=server, port=port, db=db, password=passwd, decode_responses=True)

# 管理后台通用请求头
headerAdmin = {"Content-Type": "application/json;charset=utf-8", "source": "admin", "mode": "debug"}

# 登录通用请求头
headerApp = {"Content-Type": "application/json;charset=utf-8", "source": 'web'}

# 管理员账号
admin = 18223120759
userId = find_user_id_mid(admin)


# 接口响应时间判断
def response_time(url, res):
    res_time = res.elapsed.total_seconds()
    if json_data["res_time_one"] < res_time < json_data["res_time_two"]:
        logger.info("{}接口响应时长较慢，时长为：{}".format(url, res_time))
    elif res_time >= json_data["res_time_two"]:
        logger.warning("{}接口响应时长太慢，时长为：{}".format(url, res_time))


# 所有执行前的测试数据创建
def create_all_data():
    # 创建章、节（创建客观题时需要使用）
    now = datetime.datetime.now()
    now_str = str(int(time.mktime(now.timetuple()) * 1000))
    content_chapter = "脚本使用"+now_str
    url_chapter = urlHead + '/topicapi/tmsChapter/add'
    body_chapter = {
        "content": content_chapter,
        "parentId": 10,
        "parentContent": "会计",
        "depth": 1,
        "score": 0,
        "subjectType": 1,
        "examType": 3
    }
    res_chapter = requests.post(url=url_chapter, data=json.dumps(body_chapter), headers=headerAdmin)
    response_time(url_chapter, res_chapter)
    code_chapter = res_chapter.json()['code']
    assert code_chapter == 0, res_chapter.text
    cursor.execute('select id from tms_chapter where content="%s" and exam_type=3 and subject_type=1 and depth=1' % content_chapter)
    chapter_id = cursor.fetchone()[0]
    content_section_one = "脚本第一节"+now_str
    body_section = {
        "content": content_section_one,
        "parentId": chapter_id,
        "parentContent": content_chapter,
        "depth": 2,
        "score": 0,
        "subjectType": 1,
        "examType": 3
    }
    res_section = requests.post(url=url_chapter, data=json.dumps(body_section), headers=headerAdmin)
    response_time(url_chapter, res_section)
    code_section = res_section.json()['code']
    assert code_section == 0, res_section.text
    cursor.execute('select id from tms_chapter where parent_id="%d"' % chapter_id)
    section_id = cursor.fetchone()[0]

    content_section_two = "脚本第二节" + now_str
    body_section_two = {
        "content": content_section_two,
        "parentId": chapter_id,
        "parentContent": content_chapter,
        "depth": 2,
        "score": 0,
        "subjectType": 1,
        "examType": 3
    }
    res_section_two = requests.post(url=url_chapter, data=json.dumps(body_section_two), headers=headerAdmin)
    response_time(url_chapter, res_section_two)
    code_section_two = res_section_two.json()['code']
    assert code_section_two == 0, res_section_two.text
    cursor.execute('select id from tms_chapter where parent_id="%d" and content="%s"' % (chapter_id, content_section_two))
    section_id_two = cursor.fetchone()[0]

    # 创建18道章节1下的客观题(10道模拟题，4道真题A，4道真题B)
    url_add_otopic = urlHead + '/topicapi/tmsOtopic/add'
    for i in range(18):
        if i < 4:
            paper_type = 1
        elif 4 <= i < 8:
            paper_type = 2
        else:
            paper_type = 3
        body_add_otopic = {
            "chapter": [chapter_id, section_id],
            "subjectType": 1,
            "paperType": paper_type,
            "optionType": 1,
            "combineType": 1,
            "difficultyLevel": 1,
            "year": 2020,
            "chapterId": section_id,
            "otopicExamPointQOs": [],
            "title": "节1第{}题的题干".format(i+1),
            "answerOptions": "A.第一个选项\nB.第二个选项\nC.第三个选项\nD.第四个选项",
            "answer": "A",
            "publishStatus": 2,
            "resolveContent": "<p>节1第{}题的解析</p>".format(i+1),
            "examType": 3,
            "userId": userId
        }
        res_add_otopic = requests.post(url=url_add_otopic, data=json.dumps(body_add_otopic), headers=headerAdmin)
        response_time(url_add_otopic, res_add_otopic)
        logger.info(res_add_otopic.url)
        logger.info(headerAdmin)
        logger.info(json.dumps(body_add_otopic))
        logger.info(res_add_otopic.text)
        code_add_otopic = res_add_otopic.json()['code']
        assert code_add_otopic == 0, '第{}道客观题新增失败，返回的code为{}'.format(i+1, code_add_otopic)
    # 节2创建1道模拟题
    body_add_otopic_two = {
        "chapter": [chapter_id, section_id_two],
        "subjectType": 1,
        "paperType": 3,
        "optionType": 1,
        "combineType": 1,
        "difficultyLevel": 1,
        "year": 2020,
        "chapterId": section_id_two,
        "otopicExamPointQOs": [],
        "title": "节2第1题的题干",
        "answerOptions": "A.第一个选项\nB.第二个选项\nC.第三个选项\nD.第四个选项",
        "answer": "A",
        "publishStatus": 2,
        "resolveContent": "<p>节2第1题的解析</p>",
        "examType": 3,
        "userId": userId
    }
    res_add_otopic_two = requests.post(url=url_add_otopic, data=json.dumps(body_add_otopic_two), headers=headerAdmin)
    response_time(url_add_otopic, res_add_otopic_two)
    code_add_otopic_two = res_add_otopic_two.json()['code']
    assert code_add_otopic_two == 0, '节2第1道客观题新增失败，返回的code为{}'.format(code_add_otopic_two)
    cursor.execute('select id from tms_otopic where chapter_id="%d" and paper_type != 3' % section_id)
    result_otopic_real = cursor.fetchall()
    otopic_ids_real = [result_otopic_real[i][0] for i in range(len(result_otopic_real))]  # 节1下的所有真题
    cursor.execute('select id from tms_otopic where chapter_id="%d"' % section_id)
    result_otopic = cursor.fetchall()
    otopic_ids = [result_otopic[i][0] for i in range(len(result_otopic))]  # 节1下的所有题
    cursor.execute('select id from tms_otopic where chapter_id="%d" or chapter_id="%d"' % (section_id, section_id_two))
    result_otopic_all = cursor.fetchall()
    otopic_ids_all = [result_otopic_all[i][0] for i in range(len(result_otopic_all))]  # 章下的所有题

    # 创建主观题（正常题、仅组卷；速刷题无仅组卷状态）
    url_add_stopic = urlHead+"/topicapi/tmsStopic/add"
    body_normal = {"readTime": 1,
                   "answerTime": 1,
                   "stopicQuestionQOs": [{"questionTitle": "主观题正常题的问题1",
                                          "questionScore": 0,
                                          "stopicQuestionPointQOs": [],
                                          "answerContent": "正常题的参考答案",
                                          "resolveContent":"<p>解析啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊</p>",
                                          "audioUrl":"",
                                          "videoUrl":"",
                                          "answerInput":2,
                                          "hasTextInput":1,
                                          "sequenceNum":1,
                                          "answerTable":"<table style=\"border: 1px solid #ccc; width: 100%; border-collapse: collapse; padding: 5px;\" border=\"1\" data-mce-id=\"__mce\">\n<tbody>\n<tr>\n<td style=\"width: 280.8px;\">第一空</td>\n<td style=\"width: 280.8px;\">T</td>\n<td style=\"width: 280.8px;\">&nbsp;</td>\n</tr>\n<tr>\n<td style=\"width: 280.8px;\">第二空</td>\n<td style=\"width: 280.8px;\">T</td>\n<td style=\"width: 280.8px;\">&nbsp;</td>\n</tr>\n<tr>\n<td style=\"width: 280.8px;\">第三空</td>\n<td style=\"width: 280.8px;\">T</td>\n<td style=\"width: 280.8px;\">&nbsp;</td>\n</tr>\n</tbody>\n</table>",
                                          "answerTableTemp":"<div class=\"wrap\"><table style=\"border: 1px solid #ccc; width: 1187px; border-collapse: collapse; padding: 5px;\" border=\"1\" data-mce-id=\"__mce\">\n<tbody>\n<tr>\n<td style=\"width: 280.8px;\">第一空</td>\n<td style=\"width: 280.8px;\"><div class=\"input\" contenteditable=\"true\" style=\" border: 1px solid rgb(204, 204, 204); padding: 8px; overflow: auto;\"><input style=\"display: none;\"></input></div></td>\n<td style=\"width: 280.8px;\">&nbsp;</td>\n</tr>\n<tr>\n<td style=\"width: 280.8px;\">第二空</td>\n<td style=\"width: 280.8px;\"><div class=\"input\" contenteditable=\"true\" style=\" border: 1px solid rgb(204, 204, 204); padding: 8px; overflow: auto;\"><input style=\"display: none;\"></input></div></td>\n<td style=\"width: 280.8px;\">&nbsp;</td>\n</tr>\n<tr>\n<td style=\"width: 280.8px;\">第三空</td>\n<td style=\"width: 280.8px;\"><div class=\"input\" contenteditable=\"true\" style=\" border: 1px solid rgb(204, 204, 204); padding: 8px; overflow: auto;\"><input style=\"display: none;\"></input></div></td>\n<td style=\"width: 280.8px;\">&nbsp;</td>\n</tr>\n</tbody>\n</table></div><textarea name=\"\" id=\"\" rows=\"5\"></textarea>"}],
                   "paperType": 1,
                   "publishStatus": 2,
                   "combineType": 1,
                   "topicType": 9,
                   "isVip": 0,
                   "stype": 1,
                   "title": "\\( \\infty \\leq \\frac {312} {是大发放} \\)测试脚本主观题正常题的题干",
                   "year": 2021,
                   "chapterId": chapter_id,
                   "difficultyLevel": 1,
                   "examType": 3,
                   "subjectType": 1,
                   "userId": userId
                   }
    paper_title = "测试脚本主观题仅组卷的题干"+now_str
    body_paper = {"readTime": 0,
                  "answerTime": 0,
                  "stopicQuestionQOs": [{"questionTitle": "主观题仅组卷的问题1",
                                         "questionScore": 0,
                                         "stopicQuestionPointQOs": [],
                                         "answerContent":"仅组卷的参考答案",
                                         "resolveContent":"<p>仅组卷的解析</p>",
                                         "audioUrl":"",
                                         "videoUrl":"",
                                         "answerInput":1,
                                         "hasTextInput":0,
                                         "sequenceNum":1,
                                         "answerTable":"",
                                         "answerTableTemp":""}],
                  "paperType": 1,
                  "publishStatus": 2,
                  "combineType": 2,
                  "topicType": 9,
                  "isVip": 0,
                  "stype": 1,
                  "title": paper_title,
                  "year": 2021,
                  "chapterId": chapter_id,
                  "difficultyLevel": 1,
                  "examType": 3,
                  "subjectType": 1,
                  "userId": userId
                  }
    body_quick = {"readTime": 2,
                  "answerTime": 2,
                  "stopicQuestionQOs": [{"questionTitle": "速刷题正常题的问题1",
                                         "questionScore": 0,
                                         "stopicQuestionPointQOs": [],
                                         "answerContent":"速刷题正常题的参考答案",
                                         "resolveContent":"<p>速刷题正常题的解析</p>",
                                         "audioUrl":"",
                                         "videoUrl":"",
                                         "answerInput":1,
                                         "hasTextInput":0,
                                         "sequenceNum":1,
                                         "answerTable":"",
                                         "answerTableTemp":""}],
                  "paperType": 0,
                  "publishStatus": 2,
                  "combineType": 0,
                  "topicType": 0,
                  "isVip": 0,
                  "stype": 2,
                  "title": "测试脚本速刷题的正常题题干",
                  "year": 2021,
                  "chapterId": chapter_id,
                  "difficultyLevel": 1,
                  "examType": 3,
                  "subjectType": 1,
                  "userId": userId
                  }
    res_stopic_normal = requests.post(url=url_add_stopic, json=body_normal, headers=headerAdmin)
    response_time(url=url_add_stopic, res=res_stopic_normal)
    code_stopic_normal = res_stopic_normal.json()["code"]
    assert code_stopic_normal == 0, res_stopic_normal.text
    res_stopic_paper = requests.post(url=url_add_stopic, json=body_paper, headers=headerAdmin)
    response_time(url=url_add_stopic, res=res_stopic_paper)
    code_stopic_paper = res_stopic_paper.json()["code"]
    assert code_stopic_paper == 0, res_stopic_paper.text
    res_stopic_quick = requests.post(url=url_add_stopic, json=body_quick, headers=headerAdmin)
    response_time(url=url_add_stopic, res=res_stopic_quick)
    code_stopic_quick = res_stopic_quick.json()["code"]
    assert code_stopic_quick == 0, res_stopic_quick.text
    cursor.execute('select id from tms_stopic where chapter_id="%d" and stype=1 and title !="%s"' % (chapter_id,
                                                                                                     paper_title))
    stopic_normal_id = cursor.fetchone()[0]
    cursor.execute('select id from tms_stopic where chapter_id="%d" and stype=1 and title ="%s"' % (chapter_id,
                                                                                                    paper_title))
    stopic_paper_id = cursor.fetchone()[0]
    cursor.execute('select id from tms_stopic where chapter_id="%d" and stype=2' % chapter_id)
    stopic_quick_id = cursor.fetchone()[0]

    # 创建一张试卷，关联otopic_ids_all的前2题
    paper_name = "dcc专用模考试卷啊"+now_str
    url_add_paper = urlHead+"/topicapi/tmsPaperNormal/addPaperNormal"
    body_add_paper = {"subjectType": 1,
                      "title": paper_name,
                      "time": 30,
                      "difficultyLevel": 1,
                      "type": 3,
                      "examType": 3
                      }
    res_add_paper = requests.post(url=url_add_paper, json=body_add_paper, headers=headerAdmin)
    response_time(url=url_add_paper, res=res_add_paper)
    code_add_paper = res_add_paper.json()["code"]
    assert code_add_paper == 0, res_add_paper.text
    cursor.execute('select id from tms_paper_normal where title="%s"' % paper_name)
    mock_paper_id = cursor.fetchone()[0]
    url_paper_add_topic = urlHead+"/topicapi/tmsPaperTopicNormal/assignTopicToPaper"
    body_paper_add_otopic = {"paperId": mock_paper_id,
                             "topicInfo": [{"type": 1,
                                            "topics": [{"topicId": otopic_ids_all[0],
                                                        "type": 1,
                                                        "score": 2},
                                                       {"topicId": otopic_ids_all[1],
                                                        "type": 1,
                                                        "score": 2}]
                                            }],
                             "order": True,
                             "examType": 3,
                             "subjectType": 1
                             }
    res_paper_add_topic = requests.post(url=url_paper_add_topic, json=body_paper_add_otopic, headers=headerAdmin)
    response_time(url=url_paper_add_topic, res=res_paper_add_topic)
    code_paper_add_topic = res_paper_add_topic.json()["code"]
    assert code_paper_add_topic == 0, res_paper_add_topic.text
    # 发布试卷
    url_publish_paper = urlHead+"/topicapi/tmsPaperNormal/updatePaperNormalStatus"
    body_publish_paper = {"id": mock_paper_id, "status": 2}
    res_publish_paper = requests.post(url=url_publish_paper, json=body_publish_paper, headers=headerAdmin)
    response_time(url=url_publish_paper, res=res_publish_paper)
    code_publish_paper = res_publish_paper.json()["code"]
    assert code_publish_paper == 0, res_publish_paper.text

    # 创建一个速记本题目
    url_shorthand = urlHead+"/topicapi/qtopic/add"
    body_shorthand = {"examType": 3, "subjectType": 1, "optionType": 1, "difficultyLevel": 1, "year": 2021,
                      "chapterId": section_id, "title": "速记本题目", "answer": "1", "resolve": "<p>速记本题目答案</p>",
                      "userId": userId, "publishStatus": 2}
    res_shorthand = requests.post(url=url_shorthand, json=body_shorthand, headers=headerAdmin)
    response_time(url=url_shorthand, res=res_shorthand)
    code_shorthand = res_shorthand.json()["code"]
    assert code_shorthand == 0, res_shorthand.text
    cursor.execute("select id from tms_qtopic where chapter_id={}".format(section_id))
    qtopic_id = cursor.fetchone()[0]

    # 增加返回一个客观题题号、主观题题号
    cursor.execute("select topic_number from tms_otopic where id={}".format(otopic_ids_all[0]))
    otopic_number = cursor.fetchone()[0]
    cursor.execute("select topic_number from tms_stopic where id={}".format(stopic_normal_id))
    stopic_number = cursor.fetchone()[0]

    # 将创建的所有测试数据，放到一个字典中统一返回
    data_dict = {"otopic_ids": otopic_ids, "section_id": section_id, "chapter_id": chapter_id,
                 "otopic_ids_real": otopic_ids_real, "otopic_ids_all": otopic_ids_all, "section_id_two": section_id_two,
                 "stopic": {"stopic_normal_id": stopic_normal_id, "stopic_paper_id": stopic_paper_id,
                            "stopic_quick_id": stopic_quick_id},
                 "mock_paper_id": mock_paper_id, "qtopic": qtopic_id,
                 "otopic_number": otopic_number, "stopic_number": stopic_number
                 }
    return data_dict


# 删除创建的所有测试数据
def delete_all_data(data_dict: dict):
    # 删除所创建的客观题、章节
    section_id = data_dict["section_id"]
    section_id_two = data_dict["section_id_two"]
    chapter_id = data_dict["chapter_id"]
    cursor.execute('delete from tms_otopic where chapter_id="%d" or chapter_id="%d"' % (section_id, section_id_two))
    cursor.execute('delete from tms_chapter where id="%d" or id="%d" or id="%d"' % (chapter_id, section_id,
                                                                                    section_id_two))

    # 删除创建的主观题和小问
    stopic_normal_id = data_dict["stopic"]["stopic_normal_id"]
    stopic_paper_id = data_dict["stopic"]["stopic_paper_id"]
    stopic_quick_id = data_dict["stopic"]["stopic_quick_id"]
    cursor.execute('delete from tms_stopic where id="%d" or id="%d" or id="%d"' % (stopic_normal_id, stopic_paper_id,
                                                                                   stopic_quick_id))
    cursor.execute('delete from tms_stopic_question where stopic_id="%d" or stopic_id="%d" or stopic_id="%d"' % (
        stopic_normal_id, stopic_paper_id, stopic_quick_id))

    # 删除创建的试卷
    mock_paper_id = data_dict["mock_paper_id"]
    cursor.execute('delete from tms_paper_topic_normal where paper_id={}'.format(mock_paper_id))
    cursor.execute('delete from tms_paper_normal where id={}'.format(mock_paper_id))

    # 删除速记本题目
    cursor.execute("delete from tms_qtopic where chapter_id={}".format(section_id))


# 查询用户的userId
def find_user_id(phone: int):
    cursor.execute("SELECT id FROM ums_user WHERE phone ='%d'" % phone)
    user_id = cursor.fetchone()[0]
    return user_id


# 删除用户和ums_user_exam_info
def delete_user(user_id: int):
    cursor.execute('delete from ums_user where id="%d"' % user_id)
    cursor.execute('delete from ums_user_exam_info where user_id={}'.format(user_id))


# 删除ums_user_exam_info
def delete_exam_info(user_id: int):
    cursor.execute('delete from ums_user_exam_info where user_id={}'.format(user_id))


# 数据表md5拼接
def form_md5(user_id: int, form_str: str):
    md5_user = list(hashlib.md5(str(user_id).encode('utf-8')).hexdigest())[0]
    form_name = form_str + md5_user
    return form_name




